#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>

int main(int argc, char *argv[]) {
	    if (argc != 5 || strcmp(argv[1], "-t") != 0) {
		            fprintf(stderr, "Usage: %s -t n command output_file\n", argv[0]);
			            fprintf(stderr, "n can only be 1, 2 or 3\n");
				            return 1;
					        }

	        int method = atoi(argv[2]);
		    if (method < 1 || method > 3) {
			            fprintf(stderr, "n can only be 1, 2 or 3\n");
				            return 1;
					        }

		        char *command = argv[3];
			    char *output_file = argv[4];


			        if (method == 1) {
					        int fd = open(output_file, O_WRONLY | O_CREAT | O_TRUNC, 0644);
						        if (fd == -1) {
								            perror("open");
									                return 1;
											        }
							        
							        int saved_stdout = dup(STDOUT_FILENO);
								        

								        if (dup2(fd, STDOUT_FILENO) == -1) {
										            perror("dup2");
											                return 1;
													        }
									        
									        close(fd);
										        

										        system(command);
											        

											        dup2(saved_stdout, STDOUT_FILENO);
												        close(saved_stdout);
													    }

				    else if (method == 2) {

					            FILE *saved_stdout = freopen("/dev/stdout", "w", stdout);
						            
						            if (freopen(output_file, "w", stdout) == NULL) {
								                perror("freopen");
										            return 1;
											            }
							            
							            system(command);
								         
								            freopen("/dev/stdout", "w", stdout);
									        }
				        else if (method == 3) {
						        char cmd[256];
							        snprintf(cmd, sizeof(cmd), "%s > %s", command, output_file);
								        system(cmd);
									    }

					    return 0;
}
